package pl.lodz.p.ftims.ProjektZespolowy2.managedbeans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import pl.lodz.p.ftims.ProjektZespolowy2.endpoint.EndpointLocal;
import pl.lodz.p.ftims.ProjektZespolowy2.entities.Role;
import pl.lodz.p.ftims.ProjektZespolowy2.entities.User;


@ManagedBean
@ViewScoped
public class RegistrationBean {

	@EJB
	private EndpointLocal endpoint;
	
	private User newUser;
	
	private String emailConfirmation;
	private String passwordConfirmation;
	
	private List<Role> rolesList;
	
	public RegistrationBean() {
		newUser = new User();
		rolesList = new ArrayList<Role>();
	}
	
	@PostConstruct
	public void initRolesList() {
		rolesList = endpoint.getRolesList();
	}

	public String registerNewUser() {
		boolean validationFailure = false;
		if (!newUser.getPassword().equals(passwordConfirmation)) {
			FacesContext.getCurrentInstance().addMessage("registrationForm:confirmPassword", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Podane hasła różnią się!", "Podane hasła różnią się!"));
			validationFailure = true;
		}
		if (newUser.getEmail() != null && !newUser.getEmail().equals(emailConfirmation)) {
			FacesContext.getCurrentInstance().addMessage("registrationForm:confirmEmail", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Podane adresy e-mail różnią się!", "Podane adresy e-mail różnią się!"));
			validationFailure = true;
		}
		if (validationFailure) {
			return null;
		}
		return endpoint.registerNewUser(newUser);
	}
	
	public User getNewUser() {
		return newUser;
	}

	public void setNewUser(User newUser) {
		this.newUser = newUser;
	}

	public String getEmailConfirmation() {
		return emailConfirmation;
	}

	public void setEmailConfirmation(String emailConfirmation) {
		this.emailConfirmation = emailConfirmation;
	}

	public String getPasswordConfirmation() {
		return passwordConfirmation;
	}

	public void setPasswordConfirmation(String passwordConfirmation) {
		this.passwordConfirmation = passwordConfirmation;
	}

	public List<Role> getRolesList() {
		return rolesList;
	}

	public void setRolesList(List<Role> rolesList) {
		this.rolesList = rolesList;
	}
	
}
